package com.leyou.auth.task;

import com.leyou.auth.config.JwtProperties;
import com.leyou.auth.mapper.ApplicationInfoMapper;
import com.leyou.common.auth.entity.AppInfo;
import com.leyou.common.auth.utils.JwtUtils;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

@Slf4j
@Component
public class AppTokenHolder {
    /**
     * token刷新间隔
     */
    private static final long TOKEN_REFRESH_INTERVAL = 86400000L;
    /**
     * token获取失败后重试的间隔
     */
    private static final long TOKEN_RETRY_INTERVAL = 10000L;
    @Getter
    private String token;
    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private ApplicationInfoMapper infoMapper;

    @Scheduled(fixedDelay = TOKEN_REFRESH_INTERVAL)
    public void loadTokenTask() throws InterruptedException {
        while (true) {
            try {
                // 查询服务信息
                Long serviceId = jwtProperties.getApp().getId();
                List<Long> targetIdList = infoMapper.queryTargetIdList(serviceId);
                AppInfo appInfo = new AppInfo(serviceId, jwtProperties.getApp().getName(), targetIdList);
                // 申请token
                this.token = JwtUtils.generateTokenExpireInMinutes(appInfo, jwtProperties.getPrivateKey(),
                        jwtProperties.getApp().getExpire());
                log.info("【网关服务】申请token成功！");
                break;
            } catch (Exception e) {
                log.error("【网关服务】申请token失败！");
            }
            //休眠时间
            Thread.sleep(TOKEN_RETRY_INTERVAL);
        }
    }
}
